import { NotificationWarn } from "../components/common/Notification";

const allowUploadType = ["image/gif", "image/jpeg", "image/png"];
const maxFileSize = 10 * 1024 * 1024; // 10M

const fileUpload =
  ({ type, setStatus, handleUploadFile }: any) =>
  (e: any) => {
    let file;
    if (type === "drop") {
      setStatus();
      const { dataTransfer } = e;
      file = dataTransfer.files[0];
    } else if (type === "inputUpload") {
      file = e.target.files[0];
    } else {
      const { clipboardData } = e;
      file = clipboardData?.items[0]?.getAsFile();
    }
    if (file && allowUploadType.includes(file.type)) {
      //需要时阻止默认事件 否则 粘贴文字等操作失效
      e.stopPropagation();
      e.preventDefault();
      if (file.size < maxFileSize) {
        //上传图片 获得图片地址
        handleUploadFile(file);
      } else NotificationWarn({ message: "文件最大10M" });
    }
  };

export default fileUpload;
